import Api from '../service/Api';
import {multiData, multiData2, uniqueArr, mixSend} from '../common/Function';
import {showMessages,search_div} from '../chat';
import {qunfaSendPage, qunfaPage} from './news_mass';
import {group_member_page} from './group';
import NextInput from '../component/NextInput';
import ChatManager from '../component/ChatManager';
import Session from '../service/Session';
import JsBridge from '../service/JsBridge';


function zfWay(receiver, cb) { // 转发非文本类型消息
  // 获取base64数据
//alert(`获取base64数据`)
  JsBridge.sendRequest('file.read', {
    path: window._needzf.path
  }).then(resp => {
    if (resp.success) {
      const data = resp.data;
      layer.msg('转发中', {time: 0});
      // 进行发送
      ChatManager.sendFile(receiver.ID, receiver.Name, {
        type: window._needzf.type,
        fileName: data.fileName,
        base64: data.base64
      }).then(messageId => {
        layer.closeAll();
        if (messageId === null) { // 失败
          cb.fail();
        } else { // 成功
          cb.success(messageId);
          ChatManager.pollMessage();
        }
      })
    }
  })
}


class ChoicePage {
  constructor() {

    this.GroupName = '';
    this.qunfa = false;

    this.URLs = [
      `/OrgAndUser_GetList`, // 获取单位群组人员信息
      `/RoleAndUser_GetList`, // 获取公共群组人员信息
      `/GroupUser_GetList`, // 获取个人群组人员信息
      `/DiscussGroup_GetList`, // 获取讨论组
      `/DiscussGroup_GetListByVipUser` // 获取VIP讨论组
    ];

    this._listdata = []; // 当前分页的数据
    this._arrJQ = []; // 转换的JQ列表

    this.render = this.render.bind(this);
    this.render_mulpick = this.render_mulpick.bind(this);
    this._renderTab = this._renderTab.bind(this);
    this._renderTabPage = this._renderTabPage.bind(this);
    this._normalList = this._normalList.bind(this);
    this._mulList = this._mulList.bind(this);
    this._normalList_fmt = this._normalList_fmt.bind(this);
    this._mulList_fmt = this._mulList_fmt.bind(this);
    this._mulpick_event = this._mulpick_event.bind(this);
    this._mulList_pick_event = this._mulList_pick_event.bind(this);
    this._mulpick_event2 = this._mulpick_event2.bind(this);
  }

  _mulList_fmt() {
    this._arrJQ = [];
    this._listdata.data.forEach(item => {
      item.ID = item.ID || item.User_ID || item.Group_ID;
      item.Name = item.Name || item.UserName || item.GroupName;
      if (item.ID < 0) {  // 是否有二级列表
        let root = $(`<li class='lis'><h2>${item.Name}<span></span></h2><ul class='lis_ul'></ul></li>`); // 一级列表
        root.click(function(e) {
          if(e.target.tagName !== 'SPAN') {
            e.stopPropagation();
            if (e.target.tagName === 'P'){
              return false;
            }
            const _jq = $(this);
            _jq.find('h2').eq(0).toggleClass('active')
            _jq.find('ul').eq(0).toggleClass('show')
            return false;
          }
        });
        item._c && item._c.forEach(iitem => {
          iitem.ID = iitem.ID || iitem.User_ID || iitem.Group_ID;
          iitem.Name = iitem.Name || iitem.UserName || iitem.GroupName;
          if (iitem.ID < 0) { // 是否有三级列表
            let chil1 = $(`<li class='lish'><h3>${iitem.Name}<span></span></h3><ul class='list_ul'></ul></li>`) // 二级列表
            chil1.click(function(e) {
              if(e.target.tagName !== 'SPAN') {
                e.stopPropagation();
                if (e.target.tagName === 'P'){
                  return false;
                }
                const _jq = $(this);
                _jq.find('h3').eq(0).toggleClass('active')
                _jq.find('ul').eq(0).toggleClass('show')
                return false;
              } else if (e.target.tagName === 'P'){
                return false;
              }
            });
            iitem._c && iitem._c.forEach(iiitem => {
              iiitem.ID = iiitem.ID || iiitem.User_ID || iiitem.Group_ID;
              iiitem.Name = iiitem.Name || iiitem.UserName || iiitem.GroupName;
              let chil2 = $(`<li><p data-id="${iiitem.ID}" data-name="${iiitem.Name}">${iiitem.Name}<span></span></p></li>`);
              chil2.appendTo(chil1.find('ul.list_ul'));
              chil1.appendTo(root.find('ul.lis_ul'));
            })
            !iitem._c && chil1.appendTo(root.find('ul.lis_ul'));
          } else {
              let chil1 = $(`<li><p data-id="${iitem.ID}" data-name="${iitem.Name}">${iitem.Name}<span></span></p></li>`);
              chil1.appendTo(root.find('ul.lis_ul'));
          }
        })
        this._arrJQ.push(root);
      } else {
        let root = $(`<li><p data-id="${item.ID}" data-name="${item.Name}">${item.Name}<span></span></p></li>`);
        this._arrJQ.push(root);
      }
    });
  }

  _mulList() {
    let { User_ID, Unit_ID, SessionID } = JSON.parse(localStorage.getItem("yxtUser"));
    let d1 = $.Deferred();
    multiData({
      url: {
        url: this.URLs[0],
        paramsName: `Org_ID`
      }
    }).then(data => {
      this._listdata = data;
      this._mulList_fmt();
      this._arrJQ.forEach(item => item.appendTo($('#list')));
      this._mulList_pick_event();
      d1.resolve(true);
    })
    return d1;
  }

  _mulList_pick_event() {
    // 选择事件绑定
    $('#list').on('click', 'span', function(e){

      const target = $(this).parent().parent();

      if (target.hasClass('picked')) {
        target.removeClass('picked'); // 目标元素移除选择
        // 看父元素 ul
        let ul = target.parent();
        if (ul.hasClass('list_ul')) { // target为三级元素
          target.parent().parent().removeClass('picked'); // 二级移除选择
          target.parent().parent().parent().parent().removeClass('picked'); // 一级级移除选择
        } else if (ul.hasClass('lis_ul')) { // target为二级元素
          target.parent().parent().removeClass('picked'); // 一级移除选择
          target.find('li').removeClass('picked'); // 将子集移除
        } else { // target为一级元素
          // 不做处理直接跳出
          target.find('li').removeClass('picked'); // 将子集移除
          return ;
        }
      } else {
        target.addClass('picked'); // 目标元素添加选择
        // 看父元素 ul
        let ul = target.parent();
        if (ul.hasClass('list_ul')) { // target为三级元素
          if ( target.siblings().length === target.siblings('.picked').length ) { // 如果三级元素都已选择
            let target2 = target.parent().parent();
            target2.addClass('picked'); // 二级添加选择
            if ( target2.siblings().length === target2.siblings('.picked').length ) { // 如果二级元素都已选择
              target2.parent().parent().addClass('picked');
            }
          }
        } else if (ul.hasClass('lis_ul')) { // target为二级元素
          target.find('li').addClass('picked'); // 为三级子元素添加选择

          if ( target.siblings().length === target.siblings('.picked').length ) { // 如果二级元素都已选择
            target.parent().parent().addClass('picked');
          }
        } else { // target为一级元素
          target.find('li').addClass('picked'); // 为二、三级子元素添加选择
          return ;
        }

      }

    })
  }

  _normalList_fmt() {
    console.log(`------------------listdata`)
    console.log(this._listdata.data)
    this._arrJQ = [];
    this._listdata.data.forEach(item => {
      item.ID = item.ID || item.User_ID || item.Group_ID;
      item.Name = item.Name || item.UserName || item.GroupName;
      if (item.ID < 0) {  // 是否有二级列表
        let root = $(`<li class='lis'><h2>${item.Name}</h2><ul class='lis_ul'></ul></li>`); // 一级列表
        root.click(function(e) {
          e.stopPropagation();
          const _jq = $(this);
          _jq.find('h2').eq(0).toggleClass('active')
          _jq.find('ul').eq(0).toggleClass('show')
          return false;
        })
        item._c && item._c.forEach(iitem => {
          iitem.ID = iitem.ID || iitem.User_ID || iitem.Group_ID;
          iitem.Name = iitem.Name || iitem.UserName || iitem.GroupName;
          if (iitem.ID < 0) { // 是否有三级列表
            let chil1 = $(`<li class='lish'><h3>${iitem.Name}</h3><ul class='list_ul'></ul></li>`) // 二级列表
            chil1.click(function(e) {
              e.stopPropagation();
              const _jq = $(this);
              _jq.find('h3').eq(0).toggleClass('active')
              _jq.find('ul').eq(0).toggleClass('show')
              return false;
            });
            iitem._c && iitem._c.forEach(iiitem => {
              iiitem.ID = iiitem.ID || iiitem.User_ID || iiitem.Group_ID;
              iiitem.Name = iiitem.Name || iiitem.UserName || iiitem.GroupName;
              let chil2 = $(`<li data-id="${iiitem.ID}"><p>${iiitem.Name}</p></li>`);
              chil2.click(function(e) {
                e.stopPropagation();
                $('#list').unbind('click');
                if (window._needzf) {
                  zfWay({
                    ID: iiitem.ID,
                    Name: iiitem.Name
                  }, {
                    success: (messageId) => {
                      showMessages(window._needzf.backId) // 返回来时的页面
                      layer.msg(`转发成功`, {time: 2000}) // 轻提示
                      window._needzf = null; // 转发完成清空临时载体
                    },
                    fail: () => {
                      layer.msg(`转发失败,请重试`, {time: 2000}) // 轻提示
                    }
                  })
                } else {
                  showMessages(`${$(this).data('id')}`, 1);
                }
              })
              chil2.appendTo(chil1.find('ul.list_ul'));
              chil1.appendTo(root.find('ul.lis_ul'));
            })
            !iitem._c && chil1.appendTo(root.find('ul.lis_ul'));
          } else {
              let chil1 = $(`<li data-id="${iitem.ID}"><p>${iitem.Name}</p></li>`);
              chil1.click(function(e) {
                e.stopPropagation();
                $('#list').unbind('click');
                if (window._needzf) {
                  zfWay({
                    ID: iitem.ID,
                    Name: iitem.Name
                  }, {
                    success: (messageId) => {
                      showMessages(window._needzf.backId) // 返回来时的页面
                      layer.msg(`转发成功`, {time: 2000}) // 轻提示
                      window._needzf = null; // 转发完成清空临时载体
                    },
                    fail: () => {
                      layer.msg(`转发失败,请重试`, {time: 2000}) // 轻提示
                    }
                  })
                } else {
                  showMessages(`${$(this).data('id')}`, 1);
                }
              })
              chil1.appendTo(root.find('ul.lis_ul'));
          }
        })
        this._arrJQ.push(root);
      } else {
        let root = $(`<li data-id="${item.ID}"><p>${item.Name}</p></li>`);
        root.click(function(e) {
          e.stopPropagation();
          $('#list').unbind('click');
          if (window._needzf) {
            zfWay({
              ID: item.ID,
              Name: item.Name
            }, {
              success: (messageId) => {
                showMessages(window._needzf.backId) // 返回来时的页面
                layer.msg(`转发成功`, {time: 2000}) // 轻提示
                window._needzf = null; // 转发完成清空临时载体
              },
              fail: () => {
                layer.msg(`转发失败,请重试`, {time: 2000}) // 轻提示
              }
            })
          } else {
            showMessages(`${$(this).data('id')}`, 1);
          }
        })
        this._arrJQ.push(root);
      }
    });
  }

  _normalList(type) {
    let { User_ID, Unit_ID, SessionID } = JSON.parse(localStorage.getItem("yxtUser"))
    const isQunfa = this.qunfa;
    console.log(`isQunfa------------${isQunfa}`)
    switch (type) {
      case 1: // 单位群组接口调用
        multiData({
          url: {
            url: this.URLs[0],
            paramsName: `Org_ID`
          }
        }).then(data => {
          this._listdata = data;
          console.log(`------d`)
          console.log(data)
          if (!isQunfa) {
            this._normalList_fmt();
            this._arrJQ.forEach(item => item.appendTo($('#list')));
          } else {
            this._mulList_fmt();
            this._arrJQ.forEach(item => item.appendTo($('#list')));
            this._mulList_pick_event();
          }
          this.init_search();
        });
        break;
      case 2: // 公共群组接口调用
        multiData({
          url: {
            url: this.URLs[1],
            paramsName: `Role_ID`
          }
        }).then(data => {
          this._listdata = data;
          if (!isQunfa) {
            this._normalList_fmt();
            this._arrJQ.forEach(item => item.appendTo($('#list')));
          } else {
            this._mulList_fmt();
            this._arrJQ.forEach(item => item.appendTo($('#list')));
            this._mulList_pick_event();
          }
          this.init_search();
        });
        break;
      case 3: // 个人群组接口调用
        multiData2({
          url: {
            url: this.URLs[2],
            paramsName: `Group_ID`
          }
        }).then(data => {
          console.log(data);
          this._listdata = data;
          if (!isQunfa) {
            this._normalList_fmt();
            this._arrJQ.forEach(item => item.appendTo($('#list')));
          } else {
            this._mulList_fmt();
            this._arrJQ.forEach(item => item.appendTo($('#list')));
            this._mulList_pick_event();
          }
          this.init_search();
        });
        break;
      default:
        ;
    }

  }

  _discussList() {
    const {User_ID, SessionID, Unit_ID} = JSON.parse(localStorage.getItem('yxtUser'));
    let _this = this;
    let list1 = $.Deferred(); // 讨论组列表
    let list2 = $.Deferred(); // VIP讨论组列表

    Api.get(`/BasePlate/Interface/IInterfaceJson.asmx${this.URLs[3]}`, {User_ID, SessionID, Unit_ID})
    .then(resp => {
      console.log(resp);
      if (resp && resp.Goodo && resp.Goodo.R) {
          const lists = resp.Goodo.R;
          list1.resolve(lists);
      } else {
        list1.resolve(false);
      }
    })

    Api.get(`/BasePlate/Interface/IInterfaceJson.asmx${this.URLs[4]}`, {User_ID, SessionID, Unit_ID})
    .then(resp => {
      console.log(resp);
      if (resp && resp.Goodo && resp.Goodo.R) {
          const lists = resp.Goodo.R;
          list2.resolve(lists);
      } else {
        list2.resolve(false);
      }
    })

    $.when(list1, list2).done(function(v1, v2){
      if (v1) {
        const wrapJQ = $(`<dl><dt>普通讨论组</dt></dl>`);
        v1.forEach(item => {
          const dd = $(`<dd data-id="${item.Group_ID}">${item.GroupName}</dd>`);
          dd.click(function() {
            showMessages(`-${$(this).data('id')}` ,1)
          });
          dd.appendTo(wrapJQ);
        });
        wrapJQ.appendTo($(`.choice_discuss_list`));
      }

      if (v2) {
        const wrapJQ = $(`<dl><dt>VIP权限</dt></dl>`);
        v2.forEach(item => {
          const dd = $(`<dd data-id="${item.Group_ID}">${item.GroupName}</dd>`);
          dd.click(function() {
            showMessages(`-${$(this).data('id')}` ,1)
          });
          dd.appendTo(wrapJQ);
        });
        wrapJQ.appendTo($(`.choice_discuss_list`));
      }

      _this.init_search();
    })

  }

  /**
   *  recentLists的数据结构
   *  recentLists: {
   *    User_ID: {
   *      Unit_ID: [{id:xxx, name:xxx}], // 需要获取的recentList
   *      ...
   *    },
   *    ...
   *  }
   */
  _recentList() {
    ChatManager.searchUser('')
    .then(resp => {
      console.log(resp);
      let data = resp.length > 20 ? resp.slice(0, 20) : [].concat(resp); // 最多只拉取20个
      const wrapJQ = $(`<dl></dl>`);
      data.forEach(item => {
        const dd = $(`<dd
          style="padding-left: 0; background-position: 20px center; }"
          data-id="${item.User_ID || -item.Group_ID}">${item.UserName || item.GroupName}</dd>`);
        dd.click(function() {
          if (window._needzf) {
            zfWay({
              ID: item.User_ID || item.Group_ID,
              Name: item.UserName || item.GroupName
            }, {
              success: (messageId) => {
                showMessages(window._needzf.backId) // 返回来时的页面
                layer.msg(`转发成功`, {time: 2000}) // 轻提示
                window._needzf = null; // 转发完成清空临时载体
              },
              fail: () => {
                layer.msg(`转发失败,请重试`, {time: 2000}) // 轻提示
              }
            })
          } else {
            showMessages(`${$(this).data('id')}`, 1);
          }
        });
        dd.appendTo(wrapJQ);
      });
      wrapJQ.appendTo($(`.choice_recent_list`));
      this.init_search();
    })
  }

  _renderTabPage(pageNo) {
    const isQunfa = this.qunfa;
    $('#list').unbind('click').remove();
    $('.choice_discuss_list').unbind('click').remove();
    $('.choice_recent_list').unbind('click').remove();
    switch (pageNo) {
      case 0:
        $(`<div class='choice_recent_list'></div>`).appendTo($(`.right .title`));
        this._recentList();
        break;
      case 1:
      case 2:
      case 3:
        if (!isQunfa) {
          $(`<ul id='list'></ul>`).appendTo($(`.right .title`));
        } else {
          $(`.right ul.list`).after($(`<ul id='list' class='mulpick'></ul>`));
        }

        this._normalList(pageNo);
        break;
      case 4:
        $(`<div class='choice_discuss_list'></div>`).appendTo($(`.right .title`));
        this._discussList();
        break;
      default:
        ;
    }
  }

  _renderTab() {
    const _this = this;
    const isQunfa = _this.qunfa;
    const tplJQ = $(`
      <ul class="list">
        ${isQunfa ? '' : '<li><a>最近选择人</a></li>'}
        <li class="on"><a href="###">单位群组</a></li>
        <li><a>公共群组</a></li>
        <li><a>个人群组</a></li>
        ${isQunfa ? '' : '<li><a>讨论组</a></li>'}
      </ul>
    `);

    const liArr = tplJQ.find(`li`);
    for (let i = 0; i < 5; i++) {
      liArr.eq(i).click(function() {
        liArr.removeClass(`on`);
        $(this).addClass(`on`);
        if (!isQunfa) {
          $('.right .title').find('div.search').remove();
          $('.right ul.list').after(_this._renderSearchBar(i));
          search_div();
        }
        _this._renderTabPage(i);
      })
    };

    return tplJQ;
  }

  // 创建群组
  _mulpick_event() {
    const {User_ID, SessionID, Unit_ID, UserName} = JSON.parse(localStorage.getItem('yxtUser'));
    // 返回事件
    $('.mulpick_back').click(() => {
      this.GroupName = '';
      this.render(4);
    })
    // 确认事件
    $('.mulpick_ok').click(() => {
      let idArr = [];
      let nameArr = [];
      let nameMap = {};
      $('#list').find('li.picked p').each(function(){
        const id = $(this).data('id');
        const name = $(this).data('name');
        if (id == User_ID) {
          return ;
        }
        nameMap[id] = name;
      });
      if (JSON.stringify(nameMap) === JSON.stringify({})) {
        window.layer.msg('请选择组员')
      } else {
        for (const prop in nameMap) {
          idArr.push(prop);
          nameArr.push(nameMap[prop]);
        }
        const UserIDs = idArr.join(',');
        const UserNames = nameArr.join(',');
        const GroupType = 2;
        const GroupName = this.GroupName;

        // 先创建群组
        Api.post('/BasePlate/Interface/IInterfaceJson.asmx/Group_Add', {User_ID, Unit_ID, SessionID, GroupName, GroupType, UserName})
        .then(resp => {
          if(resp && resp.Goodo && resp.Goodo.Group_ID) {
            const Group_ID = resp.Goodo.Group_ID;
            // 将人员添加到组里
            if (UserIDs) {
              Api.post('/BasePlate/Interface/IInterfaceJson.asmx/GroupUser_Add', {User_ID, SessionID, Group_ID, UserIDs, UserNames})
              .then(rresp => {
                if(rresp && rresp.Goodo && rresp.Goodo.Count) {
                  layer.msg('创建成功')
                  this.render(4);
                } else {
                  layer.msg('添加成员失败')
                  this.render(4);
                }
              })
            }

          } else {
            layer.msg('创建失败');
            this.render(4);
          }
        })


      }
    })
  }

  // 额外增加人
  _mulpick_event2({Group_ID, GroupName, hasIds}) {
    // 删除已有的组员
    $('#list').find('li p').each(function(){
      const id = `${$(this).data('id')}`;
      if (hasIds.indexOf(id) > -1) {
        $(this).parent().remove();
      }
    });
    let back_member = function() {
      group_member_page(`-${Group_ID}`, GroupName);
    }

    // 返回事件
    $('.mulpick_back').click(back_member)

    // 确认事件
    $('.mulpick_ok').click(() => {
      let idArr = [];
      let nameArr = [];
      let nameMap = {};
      $('#list').find('li.picked p').each(function(){
        const id = $(this).data('id');
        const name = $(this).data('name');
        nameMap[id] = name;
      });
      if (JSON.stringify(nameMap) === JSON.stringify({})) {
        window.layer.msg('请选择组员')
      } else {
        for (const prop in nameMap) {
          idArr.push(prop);
          nameArr.push(nameMap[prop]);
        }
        const UserIDs = idArr.join(',');
        const UserNames = nameArr.join(',');
        const {User_ID, SessionID, Unit_ID} = JSON.parse(localStorage.getItem('yxtUser'));

        // 添加到组里
        layer.msg('添加中', {time: 0});
        Api.post('/BasePlate/Interface/IInterfaceJson.asmx/GroupUser_Add', {User_ID, SessionID, Group_ID, UserIDs, UserNames})
        .then(resp => {
          if(resp.Goodo.EID == '0') {
            layer.msg('添加成功', {
              time: 2000
            }, back_member);
          } else {
            layer.msg('添加成功');
          }
        })


      }
    })
  }

  _renderSearchBar(type) {
    const _this = this;
    const isDiscussion = type === 4;
    const tplJQ = $(
      `
        <div class="search ${isDiscussion ? 'discuss' : ''}">
          <label>
            <img class="flag" src="img/news_public/search_pic.png"/><span>搜索</span>
            <input id="choice" type="text" name="sear"  value="" />
          </label>
          ${isDiscussion ? `
            <a class='toMul' href="###">+ 创建讨论组</a>
            ` : ''}
        </div>
      `
    );

    isDiscussion && tplJQ.find('.toMul').click(function(){
      NextInput.bindOk(() => {
        const GroupName = $(`.found_ip`).val();
        if (GroupName) {
          _this.GroupName = GroupName;
          _this.render_mulpick({});
          NextInput.close();
        } else {
          layer.msg('组名不能为空');
        }
      })
      NextInput.show({
        title: `创建讨论组`,
        onReady: () => {
          $(`.found_ip`).val('')
        }
      })

    })

    return tplJQ;
  }

  render(tabNo) {
    this.qunfa = false;
    const wrapJQ = $(`
      <div class="top">
        <p>选择人员</p>
      <a class="back" href="###"><img src="img/news_public/news_sys.png"/></a>
      </div>
      <div class="title">
      </div>
    `);
    // console.log(wrapJQ.find(".title").html(`ssss`));


    $(`.right`).html(wrapJQ);
    if (window._needzf) { // 如果存在转发的对象，表示从转发事件而来
      $('a.back').click(function() { // 转发的返回按钮被点击
        showMessages(window._needzf.backId) // 返回来时的页面
        window._needzf = null; // 转发完成清空临时载体
      })
    }
    this._renderTab().prependTo($(`.right .title`));

    // 渲染指定的tab页
    if (tabNo > -1 && tabNo < 5) {
      $($(`.right ul.list li`)[tabNo]).trigger('click');
    } else {
      // 渲染默认的tab页
      $($(`.right ul.list li`)[1]).trigger('click');
    }

  }

  render_qunfa(tabNo) {
    this.qunfa = true;
    const {User_ID} = Session.getUser();
    const wrapJQ = $(`
      <div class="top">
        <p>选择人员</p>
      <a class="qunfa_back"><img src="img/news_public/news_sys.png"/>返回</a>
      </div>
      <div class="title">

        <a class="news_mass_btn">确认</a>
      </div>
    `);
    // console.log(wrapJQ.find(".title").html(`ssss`));


    $(`.right`).html(wrapJQ);
    this._renderTab().prependTo($(`.right .title`));

    // 返回群发列表页
    $(`a.qunfa_back`).click(()=>{
      qunfaPage();
    })

    // 渲染指定的tab页
    if (tabNo > -1 && tabNo < 4) {
      $($(`.right ul.list li`)[tabNo]).trigger('click');
    } else {
      // 渲染默认的tab页
      $($(`.right ul.list li`)[1]).trigger('click');
    }

    $(`.right .news_mass_btn`).click(() => {
      let idArr = [];
      let nameMap = {};
      let nameArr = [];
      $('#list').find('li.picked p').each(function(){
        const id = $(this).data('id');
        const name = $(this).data('name');
        if (id == User_ID) return ;
        nameMap[id] = name;
      });

      console.log($('#list').find('li.picked p'))

      if (JSON.stringify(nameMap) === JSON.stringify({})) {
        layer.msg('发送人数过少');
        return ;
      }

      for (const prop in nameMap) {
        idArr.push(prop);
        nameArr.push(nameMap[prop]);
      }

      qunfaSendPage({ids: idArr, names: nameArr})
    })
  }

  render_mulpick({Group_ID, GroupName, groupHasIds}) {
    const wrapJQ = $(`
      <div class="top">
        <p>选择</p>
        <a class="mulpick_back"><img src="img/news_public/news_sys.png"/></a>
        <a class="confirm mulpick_ok">确认</a>
      </div>
      <div class="title">
        <ul id="list" class="mulpick">

        </ul>
      </div>
    `);


    console.log(`---------------------------------goupHasIds`)
    console.log(groupHasIds)

    $(`.right`).html(wrapJQ);

    this._mulList().then(resp => {
      if (resp) {
        if (groupHasIds && groupHasIds.length > 0) {
          this._mulpick_event2({Group_ID, GroupName, hasIds: groupHasIds});
        } else {
          this._mulpick_event();
        }
      }
    });

  }

  init_search() {
    let resultTable;
    if ($('.resultTable').length > 0) {
      resultTable = $('.resultTable');
    } else {
      resultTable = $('<div class="resultTable"></div>');
      $('.right div.search').after(resultTable);
      resultTable.css('display', 'none');
    }
    const serachInput = $('input#choice');

    // 相关事件绑定
    resultTable.on('click', function(e) {
      const target = $(e.target); // 拿到所点击的dom；
      if (target.hasClass('user')) { // 点击了人
        showMessages(target.data('id'), 1);
      } else if (target.hasClass('group')) { // 点击了组
        showMessages(-(target.data('id')), 1);
      } else if (target.hasClass('resultTable')) { // 点击了蒙层
        resultTable.css('display', 'none');
        serachInput.text('');
        serachInput.val('');
        showS();
      }
    })

    // 找到当前页面下的数据
    let datas = [];
    $('.right').find(`[data-id]`).each(function(){
      let i = $(this);
      datas.push({ID: i.data('id'), Name: i.text()})
    });

    // 隐藏输入占位块
    let hidS = function() {
      serachInput.parent().find(".flag").css({'left': '2%'});
      serachInput.parent().find("span").css({'display': 'none'});
    }
    // 恢复输入占位块
    let showS = function() {
      serachInput.parent().find(".flag").css({'left': '47%'});
      serachInput.parent().find("span").css({'display': 'block'});
    }

    serachInput.focus(function(){
      resultTable.css('display', 'block').html('');
      resultTable.html($('<dd></dd>').text('请输入关键字'));
      hidS();
    })

    // 当搜索值发生改变
    serachInput.bind("input propertychange",function(event){

        const input = $(this);
        const inputVal = input.val();
        // const history = $(".sear .history");
        // const resultBox = $(".sear .resultBox");

        if (!inputVal) { // 为空值时
          resultTable.html($('<dd></dd>').text('请输入关键字'));
          // resultTable.css('display') == 'block' &&  resultTable.css('display', 'none'); // 展示搜索历史
        } else { // 非空值时
          // 搜索消息
          let dataResult = [];
          datas.forEach(item => {
            if (item.Name.indexOf(inputVal) > -1) { // datas有搜索的关键字
              dataResult.push(item); // 推入结果
            }
          });

          let isGroup = $('div.choice_discuss_list').length > 0; // 判断当前是否在讨论组
          let tpl;
          if (dataResult.length > 0) {
            tpl = `
              <dl>
                ${dataResult.map(item => {
                  return `
                    <dd data-id="${item.ID}" class="${isGroup ? 'group' : item.ID > 0 ? 'user' : 'group'}">${item.Name.replace(new RegExp(inputVal, 'g'), '<span class="blue">' + inputVal + '</span>')}</dd>
                  `
                }).join('')}
              </dl>
            `
          } else {
            tpl = `
              <dd>未找到相关结果</dd>
            `
          }

          resultTable.html(tpl);

        }
    });

    console.log(`----------------datas`);
    console.log(datas);



  }


}


export default new ChoicePage();
